package com.guo.util;

import lombok.SneakyThrows;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @Auther Heart Guo
 * @Date 2022/03/08-16:17
 */
public class ExportTextUtil {
    @SneakyThrows
    public static void writeToTxt(HttpServletResponse response, String jsonString, String fileName){

        response.setCharacterEncoding("utf-8");

        response.setContentType("text/plain");

        response.addHeader("Content-Disposition","attachment; filename=" + new String(fileName.getBytes("gb2312"),"iso8859-1")+".txt");
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;

        try{
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(jsonString.getBytes(StandardCharsets.UTF_8));
            buff.flush();
            buff.close();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try{
                buff.close();
                outStr.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
